import datetime
import json
import re

from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework import serializers

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import RetrieveUpdateAPIView, ListAPIView, RetrieveAPIView, UpdateAPIView, CreateAPIView, \
    DestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet


from users.models import User
# from users.serializers import UserReplySerializer
from users.serializers import UserReplySerializer


def jwttoken(user):
    from rest_framework_jwt.settings import api_settings

    # 组织payload数据的方法
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    # 生成jwt token数据的方法
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    # 组织payload数据
    payload = jwt_payload_handler(user)
    # 生成jwt token
    token = jwt_encode_handler(payload)
    return token

from users.models import User
class RegisterAPIView(APIView):

    def post(self,request):
        dict=json.loads(request.body.decode())
        username=dict.get('username')
        password=dict.get('password')
        mobile=dict.get('mobile')
        sms_code=dict.get('sms_code')
        if not all([username,password,mobile,sms_code]):

            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match('^[\w-]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名格式错误'})
        if not re.match('^[a-zA-Z0-9]{8,20}$',password ):
            return JsonResponse({'code': 400, 'errmsg': '密码格式错误'})
        if not re.match('^1[345789]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不正确'})
        conn = get_redis_connection('verify_code')
        msg=conn.get(mobile)
        if msg is None:
            raise serializers.ValidationError('验证码过期')
        if sms_code != msg.decode():
            raise serializers.ValidationError('验证码有误')
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
                return JsonResponse({'errno': 400, 'errmsg': '查询数据库出错'})
        if count == 1:
            return JsonResponse({'errno': 400, 'errmsg': 'username重复'})
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '查询数据库出错'})
        if count == 1:
            return JsonResponse({'errno': 400, 'errmsg': '手机号重复'})
        try:
            user=User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '保存到数据库失败'})
        token = jwttoken(user)
        response = {'id': user.id,
                    'username': username,
                    'mobile': mobile,
                    'token': token,
                    'avatar': user.avatar}
        return Response(response)




class UserListView(RetrieveAPIView, UpdateAPIView):
    serializer_class = UserReplySerializer
    permission_classes = [IsAuthenticated]
    queryset = User.objects.all()
     # 用户详细信息
    def get_object(self):
        user = self.request.user
        replies = user.replies.all()
        user.answer_question = []
        for item in replies:
            if item.type == 2:
                user.answer_question.append(item)
                print(user)
        return user

     #修改用户信息
    def update(self, request, *args, **kwargs):
        user=self.get_object()
        serializer=self.get_serializer(instance=user,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)



# # 修改密码
# class UpadtePwdView(UpdateAPIView):
#     serializer_class = UserPwdSerializer
#     permission_classes = [IsAuthenticated]
#     # queryset = User.objects.all()
#     def get_object(self):
#         return self.request.user
#

# 上传图片
class AvatarView(View):

    def post(self, request, *args, **kwargs):
        from fdfs_client.client import Fdfs_client
        # 创建FastDFS连接对象
        client = Fdfs_client('tenthpower/utils/fastdfs/client.conf')
        # 获取前端传递的image文件
        data = request.FILES.get('img')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']
        print('http://192.168.10.129:8888/'+image_url)
        return JsonResponse(
            {
                'imgurl':'http://192.168.10.129:8888/'+image_url
            },

        )
class ChangepasswordView(UpdateAPIView):
    #修改密码
    serializer_class = UserReplySerializer
    permission_classes = [IsAuthenticated]
    queryset = User.objects.all()
    def update(self, request, *args, **kwargs):
        data=request.data
        user=request.user
        try:
            password=data.get('password')
            user.set_password(password)
            user.save()
        except Exception as e:
            return Response({"errmsg":"error"})
        serializer = self.get_serializer(instance=user)
        return Response(serializer.data)

class UserfocusView(CreateAPIView,DestroyAPIView):
    #关注和取消关注
    serializer_class = UserReplySerializer
    permission_classes = [IsAuthenticated]
    queryset = User.objects.all()
    # 关注
    def post(self, request, id):
        user =User.objects.get(id=id)
        fans = user.fans.all()
        if request.user in fans:
            user.fans.remove(request.user)
            user.save()
            return JsonResponse({'success': 'true', 'message': '取消关注'})
        else:
            user.fans.add(request.user)
            user.save()
            return JsonResponse({'success': 'true', 'message': '关注成功'})

    # 取消关注
    def delete(self, request, id):
        user =User.objects.get(id=id)
        fans = user.fans.all()
        if request.user in fans:
            user.fans.remove(request.user)
            user.save()
            return JsonResponse({'success': 'true', 'message': '取消关注'})
        else:
            user.fans.add(request.user)
            user.save()
            return JsonResponse({'success': 'true', 'message': '关注成功'})